package com.example.mq.mqserver.core;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.HashMap;
import java.util.Map;

public class Exchange {
    //交换机唯一ID
    private String name;
    //交换机类型
    private ExchangeType type = ExchangeType.DIRECT;
    //是否持久化
    private boolean durable = false;
    //交换机没人使用，自动删除
    private boolean autoDelete = false;
    //选项 TTL
    private Map<String, Object> arguments = new HashMap<String, Object>();

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public ExchangeType getType() {
        return type;
    }

    public void setType(ExchangeType type) {
        this.type = type;
    }

    public boolean isDurable() {
        return durable;
    }

    public void setDurable(boolean durable) {
        this.durable = durable;
    }

    public boolean isAutoDelete() {
        return autoDelete;
    }

    public void setAutoDelete(boolean autoDelete) {
        this.autoDelete = autoDelete;
    }

    /*
    * 把当前Map类型的argument转成String
    * spring boot项目自动集成了jacson*/
    public String getArguments(){
        ObjectMapper objectMapper = new ObjectMapper();//用来把对象转成String
        try {
            return objectMapper.writeValueAsString(arguments);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return "{}";//出现异常，返回空的字符串
    }

    //从数据库读取数据，构造Exchange对象，自动调用的方法
    public void setArguments(String argumentsJson){
        //把json转成Map对象
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            //readValue把数据转成指定类型，第二个参数用TypeReference
           this.arguments=objectMapper.readValue(argumentsJson,new TypeReference<Map<String, Object>>(){});
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }


    public void setArguments(Map<String, Object> arguments) {
        this.arguments = arguments;
    }


    //针对Arguments增加一组get set 方便在java程序中直接用
    public Object getArguments(String key){
        return arguments.get(key);
    }

    public void setArguments(String key, Object value){
        arguments.put(key,value);
    }
}
